package com.ls.jdbc.spring_jdbc;

import com.ls.jdbc.User;
import com.ls.jdbc.druid.DruidJdbcUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class Main {
    private static JdbcTemplate template = new JdbcTemplate(DruidJdbcUtils.getDataSource());

    public static void main(String[] args) {
        Main m = new Main();
        m.queryForObject();
    }

    public void queryForObject() {

        String sql = "select count(id) FROM user";
        Long list = template.queryForObject(sql,Long.class);
        System.out.println(list);

    }

    public void query() {

        String sql = "select * FROM user";
        List<User> list = template.query(sql,new BeanPropertyRowMapper<User>(User.class));
        for (User user : list) {
            System.out.println(user);
        }

    }

    public void query0() {

        String sql = "select * FROM user";
        List<User> list = template.query(sql,new RowMapper<User>(){
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String card_id = resultSet.getString("card_id");

                user.setId(id);
                user.setName(name);
                user.setCardId(card_id);
                return user;
            }
        });
        for (User user : list) {
            System.out.println(user);
        }

    }


    public void queryForList() {

        String sql = "select * FROM user";
        List<Map<String, Object>> list = template.queryForList(sql);
        for (Map<String, Object> stringObjectMap : list) {
            System.out.println(stringObjectMap);
        }

    }
    public void queryForMap() {

        String sql = "select * FROM user where id = ?";
        Map<String, Object> stringObjectMap = template.queryForMap(sql,1);
        stringObjectMap
                .forEach((k, v) -> System.out.println(k + " " + v));
    }

    public void update() {

        String sql = "update user set name = '在3' where id = ?";
        int count = template.update(sql, 1);
        System.out.println(count);
    }
}
